package com.future;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * Description: 166. 分数到小数
 * <p>
 * 分子 numerator 和分母 denominator
 * <p>
 * 示例 1：
 * <p>
 * 输入：numerator = 1, denominator = 2
 * 输出："0.5"
 * 示例 2：
 * <p>
 * 输入：numerator = 2, denominator = 1
 * 输出："2"
 * 示例 3：
 * <p>
 * 输入：numerator = 4, denominator = 333
 * 输出："0.(012)"
 * <p>
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode.cn/problems/fraction-to-recurring-decimal
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 *
 * @author weiruibai.vendor
 * Date: 2023/2/22 09:52
 */
public class Solution_166 {

    private static Solution_166 instance = new Solution_166();

    /**
     * @param numerator
     * @param denominator
     * @return
     */
    public String fractionToDecimal(int numerator, int denominator) {
        /**
         * 一定要转化成long
         */
        long numeratorLong = numerator;
        long denominatorLong = denominator;
        StringBuilder sb = new StringBuilder();
        /**
         * 计算整数部分
         */
        long intPart = numeratorLong / denominatorLong;
        /**
         * 整数部分位0，那么如果是负数，需要手工拼接'-'
         */
        if (intPart == 0 && numeratorLong * denominatorLong < 0) {
            sb.append("-");
        }
        sb.append(intPart);
        if (numeratorLong % denominatorLong != 0) {
            sb.append(".");
        }
        /**
         * 小数部分，可以忽略正负数
         */
        numeratorLong = Math.abs(numeratorLong);
        denominatorLong = Math.abs(denominatorLong);
        numeratorLong = numeratorLong % denominatorLong;
        StringBuilder point = new StringBuilder();
        /**
         * key--分子
         * val-对应的位置，当出现重复时，可以快速定位到插入"(" ")"的位置
         */
        Map<Long, Integer> map = new HashMap<>();
        int pointIndex = 0;
        while (numeratorLong != 0 && !map.containsKey(numeratorLong)) {
            map.put(numeratorLong, pointIndex++);
            numeratorLong *= 10;
            point.append(numeratorLong / denominatorLong);
            numeratorLong = numeratorLong % denominatorLong;
        }
        if (numeratorLong != 0) {
            /**
             * 说明有重复循环
             */
            Integer index = map.get(numeratorLong);
            point.insert(index, "(");
            point.append(")");
        }
        return sb.append(point).toString();
    }


    public static void main(String[] args) {

        System.out.println(Integer.MIN_VALUE);
        double d = 6 * 0.1;

        int numerator = 4;
        int denominator = 333;

        numerator = 2;
        denominator = 1;

        numerator = 2;
        denominator = 3;

        numerator = -50;
        denominator = 8;
        numerator = 7;
        denominator = -12;

        numerator = -1;
        denominator = -2147483648;
        System.out.println(instance.fractionToDecimal(numerator, denominator));
    }
}
